/*
 *  ReferenceManager.cpp
 *  ReferenceManager
 *
 *  Created by Hamza SHAWY on 20/10/07.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */
#include "Reference.h"
#include "ReferenceManager.h"
using std::cout;
using std::endl;

ReferenceManager::ReferenceManager(): Capacity(10), Size(0)
{
	RefList = new Reference[10];
}

ReferenceManager::ReferenceManager(int capac): Capacity(capac), Size(0)
{
	RefList = new Reference[capac];
}

ReferenceManager::~ReferenceManager()
{
	//frees from memory all the elements in the dynmically allocated list of References
	delete RefList;
}

int ReferenceManager::size()
{
	return Size;
}

int ReferenceManager::get(int pos)
{
	if (pos<Size && pos>=0) {
		return RefList[pos].getId();
	}
	else
		return -1;
}

//returns true if the element with the given ID is found, or false otherwise
bool ReferenceManager::search(int id)
{
	int a;
	for (a=0; a<Size; a++) {
		if (RefList[a].getId() == id) {
			return true;
		}
	}
	return false;
}

bool ReferenceManager::remove(int pos)
{	int a;
	bool result=false;
	//if the position is in the right range of stored elements
	if (pos>=0 && pos < Size) {
		//if were not removing the last element, we have to shift everything
		if (pos!=Size-1) {
			//shift all the elements on the right of us, one step leftwards
			for (a=pos; a<Size-pos-1; a++) {
				RefList[a] = RefList[a+1];
			}
		}
		//if we're removing the first element, don't do any shifting
		//->update the list's size
		Size--;
		result = true;
	}//if the indicated position is not in the right range
	else
	{
        cout << "Error: ReferenceManager::remove(int): given position out of range (should be in interval [0:" << Size -1 << "])" << endl;
		result = false;
    }
	
	return result;
}

bool ReferenceManager::add(Reference& ref)
{
	if(Size < Capacity)
	{
		RefList[Size] = ref;
		Size++;
		cout << "ReferenceManager::add(Reference&): successfully added element with id: "<<ref.getId()<<" to us" << endl;
		return true;
	}
	else {
		cout << "Error: ReferenceManager::add(Reference&): cannot add the given element as the list is full" << endl; 
		return false;
	}
		
}

//prints the contained elements' identifiers
void ReferenceManager::printIds()
{
	int a;
	cout << "<refMan instance>"<< "=>printing ids of contained items" << endl;
	for(a=0;a<Size;a++)
		cout << RefList[a].getId() << ";" << endl;
	cout << "ids for "<<a<<" elements were printed" << endl<<"</refMan instance>" << endl;
}
